package com.example.springbootvuetest.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.springbootvuetest.base.ResultCode;
import com.example.springbootvuetest.entity.Admin;
import com.example.springbootvuetest.entity.User;
import com.example.springbootvuetest.exception.MyException;
import com.example.springbootvuetest.service.IAdminService;
import com.example.springbootvuetest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 自定义拦截器
 * @Author shuoye
 * @Date 2023/3/13
 * @Version 1.0
 */
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private IAdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Admin admin;
        User user;
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new MyException(ResultCode.TOKEN_ERROR);
        }
        // 获取 token 中的 user id
        String id,password,role;
        try {
            List<String> audience = JWT.decode(token).getAudience();
            id = audience.get(0);
            role = audience.get(1);
            System.out.println("id:"+id+"role:"+role);
        } catch (JWTDecodeException j) {
            throw new MyException(ResultCode.TOKEN_ERROR);
        }
        if (role.equals("admin")) {
            admin = adminService.getById(id);
            if (admin == null) {
                throw new MyException(9003,"用户不存在，请重新登录");
            }
            password = admin.getAdminPassword();
        }
        else if(role.equals("user")) {
            user = userService.getById(id);
            if (user == null) {
                throw new MyException(9003,"用户不存在，请重新登录");
            }
            password = user.getUserPassword();
        }
        else
            throw new MyException(ResultCode.TOKEN_ERROR);
       return verityToken(token,password);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public boolean verityToken(String token,String password){
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new MyException(ResultCode.TOKEN_ERROR);
        }
        return true;
    }
}
